﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Shared.Method
{
    public class ConfigUpdate
    {
        private static readonly string BASE_PATH = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        private const string XML_FILE = "SoftwareUpdate.xml";
        private const string ROOT_NAME = "Software";


        private static void CreateXML()
        {
            //判断文件是否存在，不存在则创建，并写入基础的XML内容
            if (!File.Exists(BASE_PATH + XML_FILE))
            {
                var file = File.Create(BASE_PATH + XML_FILE);
                file.Close();
                XDocument doc = new XDocument();
                XElement ele = new XElement(ROOT_NAME);

                doc.Add(ele);
                doc.Save(BASE_PATH + XML_FILE);
            }
        }

        public static void SetXmlConfigSoftware(string name, string value)
        {
            CreateXML();
            XDocument document = XDocument.Load(BASE_PATH + XML_FILE);

            XElement root = document.Root;

            root.SetElementValue(name, value);
            document.Save(BASE_PATH + XML_FILE);
        }

        public static string GetXmlConfigSoftware(string name)
        {
            if (!File.Exists(BASE_PATH + XML_FILE) || string.IsNullOrEmpty(name))//文件不存在返回空
            {
                return null;
            }
            try
            {
                XDocument document = XDocument.Load(BASE_PATH + XML_FILE);
                XElement root = document.Root;
                return root.Element(name).Value;
            }
            catch
            {
                return null;
            }
        }
    }
}
